package com.intexh.speedandroid.module.login;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.intexh.speedandroid.R;
import com.intexh.speedandroid.base.BaseActivity;
import com.intexh.speedandroid.helper.UserBean;
import com.intexh.speedandroid.helper.UserHelper;
import com.intexh.speedandroid.net.Apis;
import com.intexh.speedandroid.net.NetworkManager;
import com.intexh.speedandroid.net.interfaces.OnRequestCallBack;
import com.intexh.speedandroid.sharesdk.ShareSdkLoginApi;
import com.intexh.speedandroid.utils.GsonUtils;
import com.intexh.speedandroid.utils.InputMethodUtils;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.sharesdk.wechat.friends.Wechat;

public class LoginActivity extends BaseActivity implements ShareSdkLoginApi.ShareLoginListener {
    @BindView(R.id.phone_et)
    EditText loginAccountEdt;
    @BindView(R.id.password_et)
    EditText loginPwdEdt;
    @BindView(R.id.login_btn)
    Button loginBtn;
    @BindView(R.id.register_tv)
    TextView loginGoToRegister;
    @BindView(R.id.forget_password_tv)
    TextView loginGoToForgetPwd;
    @BindView(R.id.third_login)
    TextView thirdLogin;
    @BindView(R.id.gap_ll)
    RelativeLayout gapLl;
    @BindView(R.id.login_we_chat_layout)
    ImageView loginWeChatLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
    }

    @OnClick({R.id.back_iv, R.id.login_btn, R.id.register_tv,
            R.id.forget_password_tv, R.id.login_we_chat_layout, R.id.login_phone_layout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_iv:
                finish();
                break;
            case R.id.login_btn:
                login();
                break;
            case R.id.register_tv:
                startActivityForResult(RegisterActivity.class,100);
                break;
            case R.id.forget_password_tv:
                startActivityForResult(ForgetPasswordActivity.class,100);
                break;
            case R.id.login_we_chat_layout:
                ShareSdkLoginApi weChat = new ShareSdkLoginApi(this);
                weChat.setPlatform(Wechat.NAME);
                weChat.login(this);
                break;
            case R.id.login_phone_layout:
                startActivityForResult(LoginByCodeActivity.class,200);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==RESULT_OK){
            if(requestCode==100){
                String phone = data.getStringExtra("phone");
                loginAccountEdt.setText(phone);
            }else if(requestCode==200){
                String response = data.getStringExtra("response");
                loginSuccess(response);
            }
        }
    }

    private void login() {
        InputMethodUtils.hideSoftInput(this);
        String account = loginAccountEdt.getText().toString();
        if(TextUtils.isEmpty(account)){
            showToast("请输入账号");
            return;
        }
        String pwd = loginPwdEdt.getText().toString();
        if(TextUtils.isEmpty(pwd)){
            showToast("请输入密码");
            return;
        }
        Map<String,String> params= new HashMap<>();
        params.put("username",account) ;
        params.put("password",pwd) ;
        showProgress();
        NetworkManager.INSTANCE.post(Apis.login, params, new OnRequestCallBack() {
            @Override
            public void onOk(String response) {
                hideProgress();
                loginSuccess(response);
            }

            @Override
            public void onError(int code,String errorMessage) {
                hideProgress();
                showHintDialog(errorMessage);
            }
        });
    }

    private void loginSuccess(String response) {
        showToast("登录成功");
        UserBean userBean = GsonUtils.jsonToBean(response,UserBean.class);
        UserHelper.login(userBean);
        finish();
    }

    @Override
    public void onShareLoginCallBack(int type, String loginType, ShareSdkLoginApi.ShareLoginBean bean) {
        runOnUiThread(() -> {
            switch (type){
                case ShareSdkLoginApi.AUTH_SUCCESS: //授权成功
                    showProgress("授权成功，正在登陆...");
                    switch (loginType) {
                        case "Wechat": //微信登录
                            startWeChatLogin(bean) ;
                            break;
                        case "QQ": //微信登录
                            startQQLogin(bean);
                            break;
                    }
                    break;
                case ShareSdkLoginApi.AUTH_FAIL:
                    showToast("授权失败,请稍后再试");
                    hideProgress();
                    break;
                case ShareSdkLoginApi.AUTH_CANCEL:
                    hideProgress();
                    showToast("取消登录");
                    break;
                case ShareSdkLoginApi.AUTH_INIT_FAIL:
                    hideProgress();
                    showToast("初始化失败");
                    break;
                case ShareSdkLoginApi.AUTH_START:
                    showProgress("正在授权..",true);
                    break;
            }
        });
    }

    //微信登录
    private void startWeChatLogin(ShareSdkLoginApi.ShareLoginBean bean) {
        HashMap<String,String> params = new HashMap<>() ;
        params.put("headimgurl",bean.getAvatar()) ;
        params.put("nickname",bean.getNickname()) ;
        params.put("openid",bean.getOpenid()) ;
        params.put("unionid",bean.getUnionid()) ;
        params.put("client","android") ;
        NetworkManager.INSTANCE.post(Apis.weChatLogin, params, new OnRequestCallBack() {
            @Override
            public void onOk(String response) {
                hideProgress();
                UserBean userBean = GsonUtils.jsonToBean(response,UserBean.class);
                UserHelper.login(userBean);
                showToast("登录成功");
                finish();
            }

            @Override
            public void onError(int code,String errorMessage) {
                hideProgress();
                showToast(errorMessage);
            }
        });
    }

    /**
     *  QQ登录
     */
    private void startQQLogin(ShareSdkLoginApi.ShareLoginBean bean) {
        HashMap<String,String> params = new HashMap<>() ;
        params.put("headimgurl",bean.getAvatar()) ;
        params.put("nickname",bean.getNickname()) ;
        params.put("openid",bean.getOpenid()) ;
        params.put("client","android") ;
        NetworkManager.INSTANCE.post(Apis.qqLogin, params, new OnRequestCallBack() {
            @Override
            public void onOk(String response) {
                hideProgress();
                UserBean userBean = GsonUtils.jsonToBean(response,UserBean.class);
                UserHelper.login(userBean);
                showToast("登录成功");
                finish();
            }

            @Override
            public void onError(int code,String errorMessage) {
                hideProgress();
                showToast("QQ登录失败，请检查网络");
            }
        });
    }
}
